package com.fjw.controller;

import com.fjw.pojo.Result;
import com.fjw.pojo.User;
import com.fjw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/regist")
    public Result regist(@RequestBody User user){
        System.out.println(user);

        User res = userService.findByUsername(user.getUsername());
        if(res != null){
            return Result.error("用户名已被占用");
        }

        userService.regist(user);
        return Result.success();
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        System.out.println(user);
        String username = user.getUsername();
        String password = user.getPassword();

        User res = userService.findByUsername(username);
        System.out.println(res);
        System.out.println(password);
        if(res == null){
            return Result.error("用户不存在");
        }
        if(Objects.equals(res.getPassword(), password)){
            return Result.success();
        }else if(!Objects.equals(res.getPassword(), password)){
            return Result.error("密码错误");
        }
        return Result.error("未知错误");
    }

    @GetMapping("/findByUsername")
    public Result findByUsername(String username){
        User res = userService.findByUsername(username);
        return Result.success(res);
    }

    @PatchMapping ("/updateById")
    public Result updateById(@RequestBody User user){
        System.out.println(user);
        User res = userService.findByUsername(user.getUsername());
        if(res!=null){
            return Result.error("用户名已被占用");
        }
        userService.updateById(user);
        return Result.success();
    }

    @PatchMapping("/updatePassword")
    public Result updatePassword(Integer id,String password){
        System.out.println(id);
        System.out.println(password);
        userService.updatePassword(id,password);
        return Result.success();
    }
}
